package cn.wenlwan.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * creator: maokai
 * on: 2018/2/22
 * description: 服务端
 */
public class EchoServer {
    private int port;

    public EchoServer (int port) {
        this.port = port;
    }

    public void run () throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group( boss , worker );
            bootstrap.channel( NioServerSocketChannel.class );
            bootstrap.childHandler( new ChannelInitializer() {
                @Override
                protected void initChannel (Channel channel) throws Exception {
                    channel.pipeline().addLast( "framer" , new DelimiterBasedFrameDecoder( 8192 , Delimiters.lineDelimiter() ) );
                    channel.pipeline().addLast( "decode" , new StringDecoder() );
                    channel.pipeline().addLast( "encoder" , new StringEncoder() );
                    channel.pipeline().addLast( new EchoWellwanServerHandler() );
                }
            } );
            bootstrap.option( ChannelOption.SO_BACKLOG , 128 );
            bootstrap.childOption( ChannelOption.SO_KEEPALIVE , true );
            // 绑定端口，开始接收进来的连接
            ChannelFuture f = bootstrap.bind( port ).sync(); // (7)

            System.out.println( "Server start listen at " + port );
            // 等待服务器  socket 关闭 。
            // 在这个例子中，这不会发生，但你可以优雅地关闭你的服务器。
            f.channel().closeFuture().sync();

        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main (String[] args) throws InterruptedException {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new EchoServer(port).run();
    }

}
